﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using SimpleSchedule.Models.Configs;

namespace SimpleSchedule.Controllers
{
    public class AuthController(ConfigProvider configProvider) : Controller
    {
        private readonly Config _config = configProvider.Config;

        [Route("Auth")]
        public IActionResult Login(string? errmsg)
        {
            if (errmsg is not null)
                ViewData["errmsg"] = errmsg;
            return View();
        }
        public async Task<IActionResult> LoginExe(string user, string pwd, string returnUrl)
        {
            var username = _config.Auth!.UserName ?? throw new Exception("用户名未配置");
            var password = _config.Auth!.Password ?? throw new Exception("密码未配置");
            if (username == user && password == pwd)
            {
                List<Claim> claims;
                claims =
                [
                    new Claim(ClaimTypes.NameIdentifier, username)
                ];
                ClaimsPrincipal userPrincipal = new(new ClaimsIdentity(claims, "User"));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddDays(7)
                });
                if (returnUrl != null)
                    return Redirect(returnUrl);
                return Redirect("/");
            }
            else
            {
                return RedirectToAction(nameof(Login), new { errmsg = "用户名或密码错误" });
            }
        }
        public IActionResult Denied()
        {
            return View();
        }
    }
}